var app = new Vue({
	el: '#app',
	data: {
		// 展示的容器名
		showCube: "medicine-view",
		// 弹出框开关控制
		dialog: {
			medicineDetail: false
		},
		// 保存用户信息
		userMsg: {
			isLogin: false,
			account: ""
		},
		// 原始的所有药品列表
		medicineMsg: [],
		// 搜索药品
		medicineSearch: "",
		// 展示药品详情
		medicineDetail: {},
		// 新增药品的属性
		medicineAdd: {
			name: "",
			amout: "",
			price: "",
			introduce: "",
			imgurl: "",
			producetime: "",
			producetimetemp: "",
			abletime: "",
			code: "",
			company: "",
			address: "",
			phone: "",
		},
		// 原始的所有账单列表
		billMsg: [],
		// 原始的所有用户列表
		clerkMsg: [],
		clerkAdd: {
			account: "",
			password: "",
			department: "",
			name: "",
			type: ""
		}
	},
	watch: {
		medicineMsg: function(){
			var myChart = echarts.init(document.getElementById('chartPie'));

			var type = {
				cold: 0,
				cough: 0,
				skin: 0,
				eyes: 0
			}

			for(var i = 0; i < this.medicineMsg.length; i++) {
				if (this.medicineMsg[i].type != undefined && this.medicineMsg[i].type != "" && this.medicineMsg[i].able == 1) {
					type[this.medicineMsg[i].type] += this.medicineMsg[i].amout;
				}
			}

			console.log(type);

			var option = {
				color: ['#c23531','#2f4554','#61a0a8','#d2a441'],
				title : {
					text: '库存药品分类占比概况',
					x:'center'
				},
				tooltip : {
					trigger: 'item',
					formatter: "{a} <br/>{b} : {c} ({d}%)"
				},
				legend: {
					orient: 'vertical',
					left: 'left',
					data: ['感冒用药类','止咳用药类','皮肤科用药类','眼科用药类']
				},
				series : [
				{
					name: '分类',
					type: 'pie',
					radius : '55%',
					center: ['50%', '60%'],
					data:[
					{value:type.cold, name:'感冒用药类'},
					{value:type.cough, name:'止咳用药类'},
					{value:type.skin, name:'皮肤科用药类'},
					{value:type.eyes, name:'眼科用药类'}
					],
					itemStyle: {
						emphasis: {
							shadowBlur: 10,
							shadowOffsetX: 0,
							shadowColor: 'rgba(0, 0, 0, 0.5)'
						}
					}
				}
				]
			};
			myChart.setOption(option);
		},
		billMsg: function(){
			var chartLine = echarts.init(document.getElementById('chartLine'));
			var chartBarPurchase = echarts.init(document.getElementById('chartBarPurchase'));
			var chartBarDamage = echarts.init(document.getElementById('chartBarDamage'));

			var now = new Date().valueOf();
			var now2 = new Date(new Date().toLocaleDateString()).valueOf() + (24*3600*1000);

			var dateData = [];

			var chartBarPurchaseData = [0,0,0,0];
			var chartBarDamageData = [0,0,0,0,0,0,0];
			var chartLineData = [
				[0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0]
			]

			for (var k = 0; k < 7; k++) {
				dateData.unshift(new Date(now - (k*24*3600*1000)).toLocaleDateString())
			}

			for (var i = 0; i < this.billMsg.length; i++) {
				var time = new Date(this.billMsg[i].create_time).valueOf();
				var j = Math.floor((now2 - time)/(24*3600*1000));
				if (j >6) {
					continue;
				} else {
					if (this.billMsg[i].type == "purchase") {
						chartBarPurchaseData[6-j] += this.billMsg[i].amout;
						if (this.billMsg[i].medicine_type == 'cold') {
							chartBarPurchaseData[0] += this.billMsg[i].amout;
 						}
						if (this.billMsg[i].medicine_type == 'cough') {
							chartBarPurchaseData[1] += this.billMsg[i].amout;
 						}
						if (this.billMsg[i].medicine_type == 'skin') {
							chartBarPurchaseData[2] += this.billMsg[i].amout;
 						}
						if (this.billMsg[i].medicine_type == 'eyes') {
							chartBarPurchaseData[3] += this.billMsg[i].amout;
 						}
					}
					if (this.billMsg[i].type == "damage") {
						chartBarDamageData[6-j] -= this.billMsg[i].amout;
					}
					if (this.billMsg[i].type == "sale") {
						if (this.billMsg[i].medicine_type == "cold") {
							chartLineData[0][6-j] += -this.billMsg[i].amout;
						}
						if (this.billMsg[i].medicine_type == "cough") {
							chartLineData[1][6-j] += -this.billMsg[i].amout;
						}
						if (this.billMsg[i].medicine_type == "skin") {
							chartLineData[2][6-j] += -this.billMsg[i].amout;
						}
						if (this.billMsg[i].medicine_type == "eyes") {
							chartLineData[3][6-j] += -this.billMsg[i].amout;
						}
					}
				}
			}

			console.log(chartBarPurchaseData)

			var chartLineOption = {
				color: ['#c23531','#2f4554','#61a0a8','#d2a441'],
				title: {
					text: '药品销售概况',
					x: 'center'
				},
				tooltip: {
					trigger: 'axis'
				},
				legend: {
					bottom: '5',
					data:['感冒用药类','止咳用药类','皮肤科用药类','眼科用药类']
				},
				grid: {
					left: '3%',
					right: '4%',
					bottom: '10%',
					containLabel: true
				},
				toolbox: {
					feature: {
						saveAsImage: {}
					}
				},
				xAxis: {
					type: 'category',
					boundaryGap: false,
					data: dateData
				},
				yAxis: {
					type: 'value'
				},
				series: [
				{
					name:'感冒用药类',
					type:'line',
					data:chartLineData[0],
        			smooth: true
				},
				{
					name:'止咳用药类',
					type:'line',
					data:chartLineData[1],
        			smooth: true
				},
				{
					name:'皮肤科用药类',
					type:'line',
					data:chartLineData[2],
        			smooth: true
				},
				{
					name:'眼科用药类',
					type:'line',
					data:chartLineData[3],
        			smooth: true
				}
				]
			};
			var chartBarPurchaseOption = {
				color: ['#c23531','#2f4554','#61a0a8','#d2a441'],
				title : {
					text: '药品采购概况',
					x:'center'
				},
				// tooltip : {
				// 	trigger: 'axis',
				// 	axisPointer : { 
				// 		type : 'shadow'
				// 	}
				// },
				grid: {
					left: '3%',
					right: '4%',
					bottom: '10%',
					containLabel: true
				},
			    xAxis: {
			        type: 'category',
			        data: ['感冒用药类','止咳用药类','皮肤科用药类','眼科用药类']
			    },
			    yAxis: {
			        type: 'value'
			    },
			    series: [{
			        data: [chartBarPurchaseData[0],0,0,0],
			        type: 'bar',
			        stack: 'total',
			        barWidth: '80'
			    },{
			        data: [0,chartBarPurchaseData[1],0,0],
			        stack: 'total',
			        type: 'bar',
			        barWidth: '80'
			    },{
			        data: [0,0,chartBarPurchaseData[2],0],
			        stack: 'total',
			        type: 'bar',
			        barWidth: '80'
			    },{
			        data: [0,0,0,chartBarPurchaseData[3]],
			        stack: 'total',
			        type: 'bar',
			        barWidth: '80'
			    }]
			};
				
			var chartBarDamageOption = {
				color: ['#c23531','#2f4554','#61a0a8','#d2a441'],
				title : {
					text: '药品报损概况',
					x:'center'
				},
				tooltip : {
					trigger: 'axis',
					axisPointer : { 
						type : 'shadow'
					}
				},
				grid: {
					left: '3%',
					right: '4%',
					bottom: '10%',
					containLabel: true
				},
			    xAxis: {
			        type: 'category',
			        data: dateData
			    },
			    yAxis: {
			        type: 'value'
			    },
			    series: [{
			        data: chartBarDamageData,
			        type: 'bar'
			    }]
			};


			chartLine.setOption(chartLineOption);
			chartBarPurchase.setOption(chartBarPurchaseOption);
			chartBarDamage.setOption(chartBarDamageOption);
		}
	},
	computed: {
		// 显示的药品列表
		showMedicineAble: function(){
			var ret = [];
			for (var i = 0; i < this.medicineMsg.length; i++) {
				if (this.medicineMsg[i].able == 1) {
					ret.push(this.medicineMsg[i]);
				}
			}
			return ret;
		},
		// 显示的药品列表
		showMedicineDisable: function(){
			var ret = [];
			for (var i = 0; i < this.medicineMsg.length; i++) {
				if (this.medicineMsg[i].able == 0) {
					ret.push(this.medicineMsg[i]);
				}
			}
			return ret;
		},
		// 显示的销售账单
		showSaleBill: function(){
			var ret = [];
			for (var i = 0; i < this.billMsg.length; i++) {
				if (this.billMsg[i].type == 'sale') {
					ret.push(this.billMsg[i])
				}
			}
			return ret;
		},
		// 显示的进货账单
		showPurchaseBill: function(){
			var ret = [];
			for (var i = 0; i < this.billMsg.length; i++) {
				if (this.billMsg[i].type == 'purchase') {
					ret.push(this.billMsg[i])
				}
			}
			return ret;
		},
		// 显示的损坏账单
		showDamageBill: function(){
			var ret = [];
			for (var i = 0; i < this.billMsg.length; i++) {
				if (this.billMsg[i].type == 'damage') {
					ret.push(this.billMsg[i])
				}
			}
			return ret;
		},
		// 显示的人员查看和管理
		showClerkAble: function(){
			var ret = [];
			for (var i = 0; i < this.clerkMsg.length; i++) {
				if (this.clerkMsg[i].able == 1) {
					ret.push(this.clerkMsg[i])
				}
			}
			return ret;
		},
		// 显示的人员查看和管理
		showClerkDisable: function(){
			var ret = [];
			for (var i = 0; i < this.clerkMsg.length; i++) {
				if (this.clerkMsg[i].able == 0) {
					ret.push(this.clerkMsg[i])
				}
			}
			return ret;
		}
	},
	methods: {
		// 点击左边栏的时候，切换显示的容器
		changeCube: function(param){
			this.showCube = param;
		},
		logout: function(){
			var self = this;
			$.post("/api/logout",{},function(data,status){
				if (data.success = "ok") {
					self.getLoginStatus();
				}
			});
		},
		// 获取登录状态
		getLoginStatus: function(){
			var self = this;
			$.get('/api/isLogin',function(data,status){
				if (data.success == "ok") {
					self.userMsg.isLogin = true;
					self.userMsg.account = data.result.account;
				} else {
					window.location.href = "/"
				}
			})
		},
		// 获取所有账单
		getBill: function(){
			var self = this;
			var data = {};
			$.post("/api/viewBill",data,function(data, status){
				if (data.success == "ok") {
					self.billMsg = data.result.data;
				}
			})
		},
		// 获取所有药品
		getMedicine: function(){
			var self = this;
			var data = {};
			$.post("/api/viewMedicine",data,function(data, status){
				if (data.success == "ok") {
					self.medicineMsg = data.result.data;
				}
			})
		},
		// 弹出药品详细详情框
		showMedicineDetail: function(a,b){
			this.medicineDetail = b;
			this.dialog.medicineDetail = true;
		},
		// 计算到期时间
		caleAbletime: function(row,column){
			return new Date((row.producetime+(row.abletime*(30*24*3600)))*1000).toLocaleDateString();
		},
		timeParse: function(row,column){
			var ret ;
			if (row.create_time != undefined) {
				ret = new Date(row.create_time).toLocaleString();
			} else if (row.createtime != undefined) {
				ret = new Date(row.createtime).toLocaleString();
			}
			return ret;
		},
		// 创建药品
		addMedicine: function(){
			console.log(this.medicineAdd);
			this.medicineAdd.producetime = this.medicineAdd.producetimetemp.valueOf()/1000;


			if (this.medicineAdd.name == "") {
				swal("保存失败", "名字不能为空", "error")
			} else if ( this.medicineAdd.price == "") {
				swal("保存失败", "价格不能为空", "error")
			} else if ( this.medicineAdd.introduce == "") {
				swal("保存失败", "介绍不能为空", "error")
			} else if ( this.medicineAdd.imgurl == "") {
				swal("保存失败", "图片不能为空", "error")
			} else if ( this.medicineAdd.producetime == "") {
				swal("保存失败", "生产日期不能为空", "error")
			} else if ( this.medicineAdd.type == "") {
				swal("保存失败", "药品类型不能为空", "error")
			} else if ( this.medicineAdd.abletime == "") {
				swal("保存失败", "有效期不能为空", "error")
			} else if ( this.medicineAdd.company == "") {
				swal("保存失败", "公司不能为空", "error")
			} else if ( this.medicineAdd.address == "") {
				swal("保存失败", "地址不能为空", "error")
			} else if ( this.medicineAdd.phone == "") {
				swal("保存失败", "电话不能为空", "error")
			} else if ( this.medicineAdd.code == "") {
				swal("保存失败", "注册代码不能为空", "error")
			} else {

				var data = {
					name: this.medicineAdd.name,
					type: this.medicineAdd.type,
					price: this.medicineAdd.price,
					introduce: this.medicineAdd.introduce,
					imgurl: this.medicineAdd.imgurl,
					producetime: this.medicineAdd.producetime,
					abletime: this.medicineAdd.abletime,
					company: this.medicineAdd.company,
					address: this.medicineAdd.address,
					phone: this.medicineAdd.phone,
					code: this.medicineAdd.code
				}

				$.post("/api/addMedicine",data,function(data, status){
					if (data.success == "ok") {
						swal("保存成功", "药品已添加", "success");
						self.getMedicine();
					} else {
						swal("保存失败", data.msg, "error");
					}
				})
			}

		},
		// 图片上传
		uploadImg: function(){
			var self = this;
			var formData = new FormData($("#uploadForm")[0]);
			console.log("执行上传事件");
			$.ajax({    
				url: '/api/upload' ,
				type: 'POST',    
				data: formData,    
				async: false,    
				cache: false,    
				contentType: false,    
				processData: false,    
				success: function (result) {
					console.log("成功");
					console.log(result)
					self.medicineAdd.imgurl = result.file_path;
				},    
				error: function (result) { 
					swal("上传失败","","error");
				}    
			}); 
		},
		// 获取所有用户
		getClerk: function(){
			var self = this;
			var data = {};
			$.post("/api/viewClerk",data,function(data, status){
				if (data.success == "ok") {
					console.log(data);
					self.clerkMsg = data.result.data;
				}
			})
		},
		// 根据type英文内容返回中文内容用于显示
		clerkType: function(row){
			var ret = "";
			if (row.department == "sales") {
				ret = "销售";
			} else if (row.department == 'check') {
				ret = '检查员';
			} else if (row.department == 'buyer') {
				ret = '采购员';
			} else {
				ret = '未设定'
			}
			return ret;
		},
		// 删除药品
		deleteMedicine: function(index, row){
			var self = this;
			var data = {
				id: row.id,
				able: 0
			}
			$.post("/api/editMedicine",data,function(data, status){
				if (data.success == "ok") {
					swal("保存成功", "药品已下架", "success");
					self.getMedicine();
				} else {
					swal("保存失败", data.msg, "error");
				}
			})
		},
		// 恢复药品
		recoverMedicine: function(index, row){
			var self = this;
			var data = {
				id: row.id,
				able: 1
			}
			$.post("/api/editMedicine",data,function(data, status){
				if (data.success == "ok") {
					swal("保存成功", "药品已上架", "success");
					self.getMedicine();
				} else {
					swal("保存失败", data.msg, "error");
				}
			})
		},
		// 删除业务员
		deleteClerk: function(index, row){
			var self = this;
			var data = {
				id: row.id,
				able: 0
			}
			$.post("/api/editClerk",data,function(data, status){
				if (data.success == "ok") {
					swal("保存成功", "数据已更改", "success");
					self.getClerk();
				} else {
					swal("保存失败", data.msg, "error");
				}
			})
		},
		// 恢复业务员
		recoverClerk: function(index, row){
			var self = this;
			var data = {
				id: row.id,
				able: 1
			}
			$.post("/api/editClerk",data,function(data, status){
				if (data.success == "ok") {
					swal("保存成功", "数据已更改", "success");
					self.getClerk();
				} else {
					swal("保存失败", data.msg, "error");
				}
			})
		},
		// 创业务员
		addClerk: function(){
			var self = this;
			this.clerkAdd.department =this.clerkAdd.type;

			if (this.clerkAdd.name == "") {
				swal("保存失败", "名字不能为空", "error")
			} else if ( this.clerkAdd.type == "") {
				swal("保存失败", "类型不能为空", "error")
			} else if ( this.clerkAdd.account == "") {
				swal("保存失败", "账号不能为空", "error")
			} else if ( this.clerkAdd.password == "") {
				swal("保存失败", "密码不能为空", "error")
			} else {

				var data = {
					name: this.clerkAdd.name,
					type: this.clerkAdd.type,
					password: this.clerkAdd.password,
					department: this.clerkAdd.department,
					account: this.clerkAdd.account
				}

				$.post("/api/addClerk",data,function(data, status){
					if (data.success == "ok") {
						swal("保存成功", "人员已添加", "success");
						self.getClerk();
					} else {
						swal("保存失败", data.msg, "error");
					}
				})
			}

		},
	},
	mounted: function(){
		var self = this;
		this.getLoginStatus();
		this.getMedicine();
		this.getBill();
		this.getClerk();
		setTimeout(function(){
			console.log("已绑定事件");
			$("#inputFile").change(function(){
				console.log("检测到上传事件，准备执行");
				self.uploadImg();
			})
		},2000)
		
	}
})